package com.quanshu.exchange.ui.gui.web_page;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.login.LoginActivity;
import com.quanshu.exchange.ui.gui.pay.AlipayActivity;
import com.quanshu.exchange.ui.gui.profile.AllOrderActivity;
import com.quanshu.exchange.ui.gui.profile.DeliveryAddressActivity;
import com.quanshu.exchange.wxapi.WXPayEntryActivity;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 购物车 --> 结算页面
 * Created by xiniu003 on 2018/1/23.
 */

public class SettleAccountActivity extends BaseActivity {

    @BindView(R.id.settle_account_webView)
    WebView mWebView;
    WebSettings mWebSettings;

    @BindView(R.id.back_llt)
    LinearLayout backLlt;

    private String goodsIdTypeNumsServiceString;//就是那个json字符串

    private String indexUrl;
//    private String backWebView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settle_account);
        ButterKnife.bind(this);

        getIntentData();
        initView();
        initEvent();
    }

    private void initEvent() {
        RxViewHelper.getInstance().clicks(backLlt, aVoid -> {
            finish();
        });
    }

    private void getIntentData() {
        Intent intent = getIntent();
        goodsIdTypeNumsServiceString = intent.getStringExtra("SETTLE_ACCOUNT");
    }

    private void initView() {
        indexUrl = Config.URL_HOST_SHOP +
                Config.create_settleAccount_goodsArr + goodsIdTypeNumsServiceString +
                Config.create_settleAccount_userd + String.valueOf(MyApplication.getInstance().getCurrentUser().getId()) +
                Config.create_shopStore_memberid + MyApplication.getInstance().getCurrentUser().getMemberid() +
                Config.create_settleAccount_fromCart;
        mWebSettings = mWebView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setTextSize(WebSettings.TextSize.NORMAL);
        mWebSettings.setDefaultTextEncodingName("UTF-8");
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.loadUrl(indexUrl);
    }

    /**
     * http://test.cattleshop.cn/cattle_exchange_simple/cart2?goodsArr=goodsArr&user_id=user_id&memberid=memberid
     */


    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("index/login/1")) {
                Intent intent = new Intent(SettleAccountActivity.this, LoginActivity.class);
                startActivity(intent);
                return true;
            }
            Uri request = Uri.parse(url);

//            if (url.contains("error/?msg")) {
//                backWebView = "error/?msg";
//            }

            if (url.contains("address/add") || url.contains("error")) {
                backLlt.setVisibility(View.VISIBLE);
            } else {
                backLlt.setVisibility(View.GONE);
            }

            try {
                if (url.equals(Config.skip_settleAccount) ||
                        url.equals(Config.skip_weixinPay_back)) {//返回上一页处理

                    finish();
                } else if (url.contains("address/add")) {//结算时，若无收货地址。当走此路径
                    Intent intent = new Intent(SettleAccountActivity.this, DeliveryAddressActivity.class);
                    intent.putExtra("FLAG", "flag");
                    startActivityForResult(intent, 12);
                } else if (url.equals(Config.URL_HOST_SHOP)) {//在微信或支付宝支付页返回

                    Intent intent = new Intent(SettleAccountActivity.this, AllOrderActivity.class);
                    startActivity(intent);
                } else if (!url.equals(Config.URL_HOST_SHOP)) {

                    if (url.contains("goApp?or")) {//牛积分支付成功路径
                        Intent intent = new Intent(SettleAccountActivity.this, AllOrderActivity.class);
                        startActivity(intent);
                    } else if (url.contains("products") || url.contains("e/cart2/")) {
                        view.loadUrl(url);
                        return false;
                    } else if (url.contains("goApp?wx")) {//前往微信
                        doWxPay(url);
                        view.loadUrl(indexUrl);
                        return true;
                    } else if (url.contains("goApp?al")) { //前往支付宝
                        doAliPay(url);
                        view.loadUrl(indexUrl);
                        return true;
                    } else {
                        return false;
                    }

                } else {
                    return false;
                }
            } catch (Exception e) {//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
            }
            return true;
        }
    }

    private void doWxPay(String url) {
        Intent intent = new Intent(SettleAccountActivity.this, WXPayEntryActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    private void doAliPay(String url) {
        Intent intent = new Intent(SettleAccountActivity.this, AlipayActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (!mWebView.canGoBack()) {
            finish();
//            return false;
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
//            mWebView.goBack(); //goBack()表示返回WebView的上一页面
            finish();
            return true;

        }
        return true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 12) {
                finish();
            }
        }
    }
}
